import dayjs, { Dayjs } from 'dayjs'
import { FormSchema } from '@/components/Form'
import { getLastLastWeek, getLastWeek, getLastWeekRange } from '@/utils/dateUtil'

export const dateOptions = [
  { label: '周', value: 'week', picker: 'week', isRange: true, format: 'GGGG-wo' },
]

const pickerObj = {
  week: 'week',
  day: 'date',
}

export const pickerType = (value) => {
  const buttonValue = (value || 'week') as keyof typeof pickerObj
  return pickerObj[buttonValue] || buttonValue
}

export const setDisabledDate = (current: Dayjs, maxDate) => {
  maxDate = maxDate || dayjs().endOf('day')
  return current && current > maxDate
}

export const getSearchFormSchema = ({ disabledOption = [''], chooseMaxDate = {} }) => {
  const filterOptions = dateOptions
  const initData = filterOptions[0]
  return [
    {
      field: 'queryType',
      label: '时间粒度',
      
      component: 'Select',
      colProps: { span: 4 },
      defaultValue: initData.value,
      componentProps: ({ formModel, formActionType }) => {
        return {
          options: filterOptions,
          allowClear: false,
          onChange: (val) => {
            const { format, picker, value } = filterOptions.filter(
              (item) => item.value === val,
            )[0]
            const { updateSchema } = formActionType
            const defaultMaxDate = chooseMaxDate[val as any] || dayjs()
            const commonProps = {
              picker,
              disabledDate: (current) => setDisabledDate(current, defaultMaxDate),
              valueFormat: format,
            }
            const defaultDate = defaultMaxDate.format(format)
            // 处理周、季、半年、年的默认值
            switch (value) {
              case 'week':
                // 计算上周周数和上上一周的周数
                formModel['[startDay,endDay]'] = getLastWeekRange()
                break
            }
            formModel.onlyStartDay = defaultDate
            updateSchema([
              {
                field: '[startDay,endDay]',
                componentProps: {
                  ...commonProps,
                },
              },
            ])
          },
        }
      },
    },
    {
      field: '[startDay,endDay]',
      label: '开始时间',
      colProps: { span: 6 },
      component: 'RangePicker',
      componentProps: {
        picker: pickerType(initData.picker),
        valueFormat: initData.format,
        defaultValue: getLastWeekRange(),
        
      },
    },
  ] as FormSchema[]
}
